package com.fjnu.aspect;
import com.fjnu.annotation.NPECatch;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
@Aspect
@Component
public class LoggingAndExceptionAspect {
    private static final Logger logger = LoggerFactory.getLogger(LoggingAndExceptionAspect.class);
    @Around("execution(* com.fjnu.dao.impl.UserDaoImpl.*(..))")
    public Object logAndCatch(ProceedingJoinPoint joinPoint) throws Throwable {
        long startTime = System.currentTimeMillis();
        String methodName = joinPoint.getSignature().getName();

        try {
            Object result = joinPoint.proceed(); // 执行目标方法
            long endTime = System.currentTimeMillis();
            double duration = (endTime - startTime) / 1000.0;
            logger.info("[INFO] [{}] method was executed and spent {} second.", 
                        java.time.LocalDateTime.now(), 
                        duration);
            return result;
        } catch (Exception e) {
            boolean hasAnnotation = joinPoint.getTarget().getClass().isAnnotationPresent(NPECatch.class) ||
                                    joinPoint.getSignature().getDeclaringType().getMethod(methodName, 
                                    ((org.aspectj.lang.reflect.MethodSignature) joinPoint.getSignature()).getParameterTypes())
                                    .isAnnotationPresent(NPECatch.class);
            if (hasAnnotation) {
                logger.info("[INFO] Exception in method: {} with message: {}", methodName, e.getMessage(), e);
            }
            return null;
        }
    }
}
